import React, { useState, useEffect, useMemo } from 'react';
import { Modal, Tree, Button, Space } from 'antd';
import type { TreeProps } from 'antd';
import { getAllTreeKeys } from '../utils/treeUtils';
import TableSelectModal from './TableSelectModal';
import menuData from './menu.json';

interface MergeModalProps {
  visible: boolean;
  onCancel: () => void;
  treeData: any[];
  onConfirm: (selectedKeys: string[]) => void;
  preSelectedKeys?: string[]; // 预选中的节点
}

const MergeModal: React.FC<MergeModalProps> = ({
  visible,
  onCancel,
  treeData,
  onConfirm,
  preSelectedKeys = [],
}) => {
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [tableSelectVisible, setTableSelectVisible] = useState(false);

  // 当弹窗打开时，自动展开所有节点并设置预选中的节点
  useEffect(() => {
    if (visible && treeData.length > 0) {
      setExpandedKeys(getAllTreeKeys(treeData));
      setCheckedKeys(preSelectedKeys);
    }
  }, [visible, treeData, preSelectedKeys]);

  const onCheck: TreeProps['onCheck'] = (checkedKeysValue) => {
    // 当checkStrictly为true时，checkedKeysValue是一个对象 {checked: string[], halfChecked: string[]}
    // 当checkStrictly为false时，checkedKeysValue是一个数组 string[]
    if (Array.isArray(checkedKeysValue)) {
      setCheckedKeys(checkedKeysValue);
    } else {
      setCheckedKeys(checkedKeysValue.checked || []);
    }
  };

  const onExpand: TreeProps['onExpand'] = (expandedKeysValue) => {
    setExpandedKeys(expandedKeysValue as string[]);
  };

  // 根据选中的节点keys提取currentCompanyUscc和mergeType数据
  const getSelectedNodesData = (selectedKeys: string[]) => {
    const result: Array<{currentCompanyUscc: string, mergeType: number}> = [];
    
    const findNodeData = (nodes: any[], targetKey: string): any => {
      for (const node of nodes) {
        if (node.key === targetKey) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          const found = findNodeData(node.children, targetKey);
          if (found) return found;
        }
      }
      return null;
    };
    
    selectedKeys.forEach(key => {
      const nodeData = findNodeData(treeData, key);
      if (nodeData && nodeData.bsdwxydms && nodeData.mergeType !== undefined) {
        result.push({
          currentCompanyUscc: nodeData.bsdwxydms,
          mergeType: nodeData.mergeType
        });
      }
    });
    
    return result;
  };

  const handleSelectTable = () => {
    console.log('选表操作，已选择的节点:', checkedKeys);
    setTableSelectVisible(true);
  };

  const handleTableSelectConfirm = (selectedTables: string[]) => {
    console.log('选择的表格:', selectedTables);
    const selectedNodesData = getSelectedNodesData(checkedKeys);
    console.log('提取的节点数据:', selectedNodesData);
    setTableSelectVisible(false);
    // 合并成功后关闭 MergeModal
    onCancel();
  };

  const handleTableSelectCancel = () => {
    setTableSelectVisible(false);
  };

  // 表格数据 - 整合审定财务数据和menu.json数据
  const tableData = useMemo(() => {
    // 审定财务数据
    const auditFinanceData = [
      {
        tabName: '资产',
        tabKey: '1',
        isVerify: false,
        closable: false,
        propsData: {
          tableName: '审定财务-资产表',
          titleName: '资产负债表',
          WscwbbType: '资产类',
          origin: '审定财务',
          tabsIndex: 1,
        }
      },
      {
        tabName: '负债',
        tabKey: '2',
        isVerify: false,
        closable: false,
        propsData: {
          tableName: '审定财务-负债表',
          titleName: '资产负债表（续）',
          WscwbbType: '负债类',
          origin: '审定财务',
          tabsIndex: 2,
        }
      },
      {
        tabName: '利润',
        tabKey: '3',
        isVerify: false,
        closable: false,
        propsData: {
          tableName: '审定财务-利润表',
          titleName: '利润表',
          WscwbbType: '损益类',
          origin: '审定财务',
          tabsIndex: 3,
        }
      },
      {
        tabName: '现流',
        tabKey: '4',
        isVerify: false,
        closable: false,
        propsData: {
           tableName: '审定财务-现金流量表',
           titleName: '现金流量表',
           WscwbbType: '附注与分析',
           origin: '审定财务',
           tabsIndex: 4,
         }
       },
       {
         tabName: '现流附',
         tabKey: '5',
         isVerify: false,
         closable: false,
         propsData: {
           tableName: '审定财务-现金流补充资料表',
           titleName: '现金流量表补充资料',
           WscwbbType: '附注与分析',
           origin: '审定财务',
           tabsIndex: 5,
           actionCol: 2,
         }
       },
       {
         tabName: '权益变动(本年)',
         tabKey: '6',
         isVerify: false,
         closable: false,
         propsData: {
           tableName: '审定财务-所有者权益变动表_本年',
           titleName: '所有者权益变动表',
           WscwbbType: '附注与分析',
           origin: '审定财务',
           tabsIndex: 6,
         }
       },
       {
         tabName: '权益变动(上年)',
         tabKey: '7',
         isVerify: false,
         closable: false,
         propsData: {
           tableName: '审定财务-所有者权益变动表_上年',
           titleName: '所有者权益变动表(续)',
           WscwbbType: '附注与分析',
           origin: '审定财务',
           tabsIndex: 7,
         }
       }
    ];

    // 转换menu.json数据为tableData格式
     const menuTableData = menuData.data.map((item, index) => {
       // 根据type字段确定分类
       let category = '附注与分析';
       if (item.type === 'asset') {
         category = '资产类';
       } else if (item.type === 'liability') {
         category = '负债类';
       } else if (item.type === 'profit') {
         category = '损益类';
       }

      return {
        // menu.json数据的字段
        id: item.id,
        title: item.title,
        name: item.name,
        type: item.type,
        category: category,
        associatedReport: item.config?.tableInfo?.associatedReport || '',
        
        // 兼容原有格式的字段
        tabName: item.name,
        tabKey: `menu_${item.id}`,
        isVerify: false,
        closable: false,
        propsData: {
          tableName: item.title,
          titleName: item.name,
          WscwbbType: category,
          origin: 'menu',
          tabsIndex: index + 100, // 避免与审定财务数据的tabsIndex冲突
        }
      };
    });

    // 合并两个数据源
    return [...auditFinanceData, ...menuTableData];
  }, []);

  const handleMerge = () => {
    console.log('合并操作，已选择的节点:', checkedKeys);
    onConfirm(checkedKeys);
    onCancel();
  };

  const handleCancel = () => {
    setCheckedKeys([]);
    setExpandedKeys([]);
    onCancel();
  };

  return (
    <Modal
      title="合并报表"
      open={visible}
      onCancel={handleCancel}
      width={800}
      footer={null}
      destroyOnClose
    >
      <div style={{ display: 'flex', height: '400px' }}>
        {/* 左侧树形结构 */}
        <div style={{ flex: 1, borderRight: '1px solid #e5e5e5', paddingRight: '16px' }}>
          <div style={{ marginBottom: '12px', fontWeight: 'bold' }}>选择合并单位</div>
          <Tree
            checkable
            checkStrictly
            onCheck={onCheck}
            checkedKeys={checkedKeys}
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            treeData={treeData}
            style={{
              height: '350px',
              overflow: 'auto',
              border: '1px solid #d9d9d9',
              borderRadius: '4px',
              padding: '8px'
            }}
          />
        </div>
        
        {/* 右侧操作按钮 */}
        <div style={{ width: '200px', paddingLeft: '16px', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            <Button 
              type="default" 
              block
              onClick={handleSelectTable}
              disabled={checkedKeys.length === 0}
            >
              选表
            </Button>
            <Button 
              type="primary" 
              block
              onClick={handleMerge}
              disabled={checkedKeys.length === 0}
            >
              合并
            </Button>
          </Space>
        </div>
      </div>
      
      <TableSelectModal
        visible={tableSelectVisible}
        onCancel={handleTableSelectCancel}
        onConfirm={handleTableSelectConfirm}
        tableData={tableData}
        companyTreeStructure={getSelectedNodesData(checkedKeys)}
      />
    </Modal>
  );
};

export default MergeModal;